# coding=utf-8
#


import json
import types

from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.cvm.v20170312 import cvm_client, models

from iminer.tidal.models import TidalAgent


TX_API_AK = "AKIDIarCd1C3HdwAU9zux7IjDqhCsegpGoP5"
TX_API_SK = "waHxZdfzSh8iIHGKd8xtUzfbgOTc7rfa"

instance_ids = open("ecs.txt").readlines()


instance_zone_dict = {}

for instance_id in instance_ids:
    ta = TidalAgent.objects.filter(instance_id=instance_id.strip()).first()
    if ta:
        key = "%s_%s" % (ta.endpoint, ta.zone)
        instance_zone_dict.setdefault(key, []).append(ta.instance_id)


cred = credential.Credential(TX_API_AK, TX_API_SK)

for instance_info, instance_id_list in instance_zone_dict.items():
    endpoint, zone = instance_info.split("_")
    httpProfile = HttpProfile()
    httpProfile.endpoint = endpoint

    # 实例化要请求产品的client对象,clientProfile是可选的
    client = cvm_client.CvmClient(cred, zone)
    for i in range(0, len(instance_id_list), 50):
        cur_slice = instance_id_list[i:i+50]

        req = models.RebootInstancesRequest()
        params = {
            "InstanceIds": cur_slice,
            "ForceReboot": True
        }
        req.from_json_string(json.dumps(params))

        # 返回的resp是一个RebootInstancesResponse的实例，与请求对象对应
        resp = client.RebootInstances(req)
        # 输出json格式的字符串回包
        print(resp.to_json_string())
